require 'rubygems'
require 'gruff'
require "report/Report"
require "report/Section"

class SetPerformance

  NAME = "Performance (Set)"
  def analyze(directory, experimentalData, phraseCards, normalize=true)

    #create the report
    reportname = normalize ? NAME + " (Normalized)" : NAME
    report = Report.new(directory, reportname )

    #get the data by set
    data = experimentalData.group_by_set

    data.each_pair do |set, entries|
      data_by_uid = {}

      entries.each do |e|
        #initialize if nil
        data_by_uid[e.uid] ||= []
        data_by_uid[e.uid] << e
      end

      #create a graph for each set
      g = create_graph(set)

      #do some simple statistics
      stat = ""

      #Generate a section for each tech uid
      data_by_uid.each_pair do |uid, entries|
        entries.sort! { |x,y| x.date <=> y.date }
        if normalize
          durations = entries.collect do |e|
            e.duration.to_f / phraseCards.getPhrase(e.set, e.phrase).length
          end
        else
          durations = entries.collect {|e| e.duration}
        end
        avg = durations.inject{ |sum, el| sum + el }.to_f / durations.length
        g.data "UID:#{uid}", durations
        stat = stat + "<b>UID #{uid}:</b> " +
        "finished(phrases):#{entries.length} " +
        "average time: #{avg}" +
        (normalize ? " per character" : "") +
        "<br/>"
      end

      report.new_section("Set #{set}", stat, g)

    end

    #generate report
    report.to_html
  end

  def create_graph (set)
    g = Gruff::Line.new
    g.dot_radius = 2
    g.line_width = 2
    g.x_axis_label = "Phrases"
    g.y_axis_label = "Time (10 ms)"
    g.title = "Performance (Set:#{set})"
    g
  end

end
